package com.dabao.service.impl;

import com.dabao.dao.BaseDao;
import com.dabao.query.BaseQuery;
import com.dabao.service.BaseService;
import com.dabao.util.ReflectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.List;

/**
 * Created by card on 16/4/15.
 */
public class BaseServiceImpl<T, Q extends BaseQuery> implements BaseService<T, Q> {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    protected BaseDao<T, Q> dao;

    public int insert(T t) {
        return dao.insert(t);
    }

    public int update(T t) {
        return dao.update(t);
    }

    public T selectById(Integer id) {
        Type[] types = ReflectionUtils.getParameterizedTypes(this);
        if(types != null && types.length == 2) {
            try {
                Q query = (Q) ReflectionUtils.newInstance(types[1]);
                Class clazz = ReflectionUtils.getClass(types[1]);
                Field field = clazz.getDeclaredField("id");
                field.setAccessible(true);
                field.set(query, id);
                List<T> ts = selectList(query);
                return ts.size() > 0 ? ts.get(0) : null;
            } catch (Exception e) {
                logger.error("selectById error", e);
            }
        }
        return null;
    }

    public List<T> selectList(Q q) {
        return dao.selectList(q);
    }

    public int selectCount(Q q) {
        return dao.selectCount(q);
    }

    public int delete(Integer id) {
        return dao.delete(id);
    }
}
